﻿using MemberManagement.Common;
using MemberManagement.Context;
using MemberManagement.Entity;
using MemberManagement.Model;
using MemberManagement.UserControls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MemberManagement
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();

            this.dataGridView1.AutoGenerateColumns = false;
            DataGridViewActionButtonColumn dataGridViewColumn = new DataGridViewActionButtonColumn();
            dataGridViewColumn.DefaultCellStyle.BackColor = Color.White;
            dataGridViewColumn.Width = 180;
            dataGridViewColumn.HeaderText = "操作";
            dataGridViewColumn.Resizable = DataGridViewTriState.False;
            this.dataGridView1.Columns.Add(dataGridViewColumn);
            this.dataGridView1.Columns["colCreateTime"].DefaultCellStyle.Format = "yyyy-MM-dd hh:mm:ss";
            this.Text = Helper.GetSystemTitle();
        }

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText == "操作")
            {
                DataGridViewActionButtonColumn dataGridViewColumn = (DataGridViewActionButtonColumn)this.dataGridView1.Columns[e.ColumnIndex];
                var cell = this.dataGridView1.Rows[e.RowIndex].Cells["colId"];
                var buttonList = dataGridViewColumn.ButtonList.Where(b => b.MouseOnButton); // 鼠标悬浮在上面的按钮
                foreach (ActionButton act in buttonList)
                {
                    if (act.Name.ToLower() == "update")
                    {
                        ShowCreateMemberForm(cell.Value.ToString());
                    }
                    else if (act.Name.ToLower() == "recharge")
                    {
                        ShowRechargeForm(cell.Value.ToString());
                    }
                    else if (act.Name.ToLower() == "consumption")
                    {
                        ShowConsumptionForm(cell.Value.ToString());
                    }
                }

            }
        }


        private void pager_EventPaging(EventArgs e)
        {
            LoadData();
        }

        #region 发卡
        private void 发卡ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowCreateMemberForm();
        }

        private void ShowCreateMemberForm(string memberId = null)
        {
            var frm = new CreateMemberForm();
            frm.MemberId = memberId;
            //frm.MdiParent = this;
            //frm.Owner = this;
            frm.FormClosed += (s,e) => 
            {
                this.LoadData();
            };
            frm.ShowDialog();
        }
        #endregion

        #region 充值 
        private void 充值ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowRechargeForm();
        }

        private void ShowRechargeForm(string memberId = null)
        {
            var frm = new RechargeForm();
            frm.MemberId = memberId;
            //frm.MdiParent = this;
            //frm.Owner = this;
            frm.FormClosed += (s, e) =>
            {
                this.LoadData();
            };
            frm.ShowDialog();
        }


        #endregion

        #region 扣费
        private void 扣费ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowConsumptionForm();
        }

        private void ShowConsumptionForm(string memberId = null)
        {
            var frm = new ConsumptionForm();
            frm.MemberId = memberId;
            //frm.MdiParent = this;
            //frm.Owner = this;
            frm.FormClosed += (s, e) =>
            {
                this.LoadData();
            };
            frm.ShowDialog();
        }
        #endregion


        private void MainForm_Load(object sender, EventArgs e)
        {
            this.dateTimePicker1.Value = DateTime.Now.AddYears(-1);
            this.dateTimePicker2.Value = DateTime.Now;
            LoadData();
        }

        private bool LoadData()
        {
            try
            {
                using (var db = new MyContext())
                {
                    var startTime = DateTime.Parse(this.dateTimePicker1.Value.ToString("yyyy-MM-dd 00:00:00"));
                    var endTime = DateTime.Parse(this.dateTimePicker2.Value.ToString("yyyy-MM-dd 23:59:59"));
                    var query = db.Member.Where(m => m.CreateTime >= startTime && m.CreateTime <= endTime)
                        .OrderByDescending(m => m.CreateTime)
                        .AsQueryable();
                    if (!string.IsNullOrEmpty(txtName.Text))
                    {
                        query = query.Where(m => m.Name.Contains(txtName.Text));
                    }
                    if (!string.IsNullOrEmpty(this.txtCard.Text.Trim()))
                    {
                        query = query.Where(m => m.IdCard.Contains(this.txtCard.Text) || m.Mobile.Contains(this.txtCard.Text));
                    }
                    this.pager.TotalCount = query.Count();
                    var result = query.Skip((this.pager.CurrentPage - 1) * this.pager.PageSize).Take(this.pager.PageSize)
                        .Select(m => new MemberQueryModel
                        { 
                            Id = m.Id,
                            Name = m.Name,
                            CardNumber = m.CardNumber,
                            IdCard = m.IdCard,
                            Balance = m.Balance,
                            Mobile = m.Mobile,
                            CreateTime = m.CreateTime
                        })
                        .ToList();
                    this.dataGridView1.DataSource = result;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.LoadData();
        }

        private void 充值扣费记录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frm = new RechargeHistoryForm();
            frm.ShowDialog();
        }

        private void 参数设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frm = new SysConfigForm();
            frm.ShowDialog();
        }
        #region 导出
        private void likExport_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.saveFileDialog1.FileName = DateTime.Now.ToString("yyMMddHHmmss");
            if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    using (var db = new MyContext())
                    {
                        var startTime = DateTime.Parse(this.dateTimePicker1.Value.ToString("yyyy-MM-dd 00:00:00"));
                        var endTime = DateTime.Parse(this.dateTimePicker2.Value.ToString("yyyy-MM-dd 23:59:59"));
                        var query = db.Member.Where(m => m.CreateTime >= startTime && m.CreateTime <= endTime)
                            .OrderByDescending(m => m.CreateTime)
                            .AsQueryable();
                        if (!string.IsNullOrEmpty(txtName.Text))
                        {
                            query = query.Where(m => m.Name.Contains(txtName.Text));
                        }
                        if (!string.IsNullOrEmpty(this.txtCard.Text.Trim()))
                        {
                            query = query.Where(m => m.IdCard.Contains(this.txtCard.Text) || m.Mobile.Contains(this.txtCard.Text));
                        }
                        var result = query.Select(m => new MemberQueryModel
                            {
                                Id = m.Id,
                                Name = m.Name,
                                CardNumber = m.CardNumber,
                                IdCard = m.IdCard,
                                Balance = m.Balance,
                                Mobile = m.Mobile,
                                CreateTime = m.CreateTime
                            }).ToList();
                        Helper.ExportExcel(result, GetColumns(), this.saveFileDialog1.FileName);
                    }

                    MessageBox.Show("导出成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "操作数据失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private Dictionary<string, string> GetColumns()
        {
            return new Dictionary<string, string>
            {
                { "Name","姓名"},
                { "CardNumber","卡号"},
                { "Mobile","手机号"},
                { "IdCard","身份证号"},
                { "Balance","余额(元)"},
                { "CreateTime","发卡日期"},
            };
        }
        #endregion
    }
}
